package com.front.web.mall;

import com.alibaba.fastjson.JSONObject;
import com.bootdo.common.utils.*;
import com.bootdo.common.wxpay.CommonUtil;
import com.bootdo.common.wxpay.WxPayHelper;
import com.bootdo.common.wxpay.XMLUtils;
import com.bootdo.haojiangboutils.MapBuild;
import com.bootdo.haojiangboutils.ResultReBuild;
import com.bootdo.lvyou.domain.LvyouScenicTicketOrder;
import com.bootdo.lvyou.domain.LvyouSpecialtyEnclosure;
import com.bootdo.mall.domain.*;
import com.bootdo.member.domain.ShequMember;
import com.bootdo.websocket.WebSocketServer;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

@RequestMapping("/f/mall/web/v1")
@RestController
public class MallWebControllerV1 extends MallSupperController {
    public static final String WXPAYOK="<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
    public static final String WXPAYNO="<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[支付失败]]></return_msg></xml>";

    /**
     * http://127.0.0.1:8090/f/mall/web/v1/getfirstCategory
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("getfirstCategory")
    public R getCategory(
            HttpServletRequest request,
                         HttpServletResponse response){
        List<MallCateGory> list =  mallCateGoryService.list(MapBuild.getInstand()
                .setKV("parentId", 1)
                );
        return R.ok().put("l", new ResultReBuild<MallCateGory>()
                .toNewObj(list,
                        new String []
                                {"id","name","lables","pic"}) );
    }



    /**
     * 得到二级分类 和 其子分类
     * http://127.0.0.1:8090/f/mall/web/v1/gettwoCategory?categoryId=88
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("gettwoCategory")
    public R getGoodByCategoryId(
            @RequestParam("categoryId") Long categoryId,
            HttpServletRequest request,
            HttpServletResponse response){
        List<MallCateGory> list =  mallCateGoryService.list(MapBuild.getInstand()
                .setKV("parentId", categoryId)
        );
        if(null != list){
            list.forEach(item ->{
                List<MallCateGory> cc =   mallCateGoryService.list(MapBuild.getInstand()
                        .setKV("parentId", item.getId()));
                item.setChildren(cc);
            });
        }
        return R.ok().put("l",  new ResultReBuild<MallCateGory>()
                .toNewObj(list,
                        new String []
                                {"id","name","lables","pic","children"}) );
    }



    /**
     * http://127.0.0.1:8090/f/mall/web/v1/getGoodList?categoryId=107&pageNo=0&pageSize=10

     * @param categoryId
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("getGoodList")
    public R getGoodList(
            @RequestParam(value = "categoryId",defaultValue = "") Long categoryId,
            @RequestParam("pageNo") Integer pageNo,
            @RequestParam("pageSize") Integer pageSize,
            HttpServletRequest request,
            HttpServletResponse response){

        Map query =  MapBuild.getInstand().setKV("categoryId", categoryId);

        String field = request.getParameter("field");
        String sort = request.getParameter("sort");
        String name = request.getParameter("name");
        if(StringUtils.isEmpty(field)){
            field = "salesNum";
        }
        if(StringUtils.isNotBlank(name)){
            query.put("name",name);
        }
        if(StringUtils.isEmpty(sort)){
            sort = "desc";
        }
        query.put("field",field);
        query.put("sort",sort);
        query.put("pageNo",pageNo * pageSize);
        query.put("pageSize",pageSize);

        int count =  mallGoodService.getGoodCountByCategoryId(query);
        int pageSum=(count-1)/pageSize+1;
        if(pageNo > pageSum-1){
            return R.error("没有更多了");
        }

        List<MallGood>  mallGoods  =  mallGoodService.getGoodListByCategoryId(query);
        if(mallGoods.size() <= 0){
            return R.error("没有更多了");
        }
        return R.ok().put("l", mallGoods);
    }



    /**
     * http://127.0.0.1:8090/f/mall/web/v1/getGoodDetail?goodId=19
     * @param goodId
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("getGoodDetail")
    public R getGoodDetail(
            @RequestParam("goodId") Long goodId,
            @RequestParam("memberMobile") String memberMobile,
            HttpServletRequest request,
            HttpServletResponse response){
        MallGood   mallGood  =   mallGoodService.get(goodId);
        List<GoodSpecs> goodSpecs =  goodSpecsService.list(MapBuild.getInstand().setKV("goodId", mallGood.getId()));
        goodSpecs.stream().forEach(item ->{
            Object obj =  redisUtil.hget("GOODCARD_"+memberMobile, goodId+"_"+item.getId());
            if(null != obj){
                item.setGoodCartNum(((MallGood)obj).getGoodCartNum());
            }else{
                item.setGoodCartNum(0);
            }
        });
        mallGood.setGoodSpecs(goodSpecs);
        if( mallGood.getGoodSpecs().size() > 0){
            AtomicInteger stock = new AtomicInteger();
            AtomicInteger salesNum = new AtomicInteger();
            mallGood.getGoodSpecs().forEach(item ->{
                stock.addAndGet(item.getStock());
                salesNum.addAndGet(item.getSalesNum());
            });
            mallGood.setPrice(mallGood.getGoodSpecs().get(0).getPrice());
            mallGood.setIntegral(mallGood.getGoodSpecs().get(0).getIntegral());
            mallGood.setStock(stock.get());
            mallGood.setReturnIntegral(mallGood.getGoodSpecs().get(0).getReturnIntegral());
            mallGood.setSalesNum(salesNum.get());
        }

        List<LvyouSpecialtyEnclosure> l =   lvyouSpecialtyEnclosureService
                .list(MapBuild.getInstand().setKV("keyStr",goodId).setKV("type", "2"));
        return R.ok().put("i", mallGood).put("banner",new ResultReBuild<LvyouSpecialtyEnclosure>().toNewObj(l, new String[]{
                "fileUrl"
        }));
    }





   /* Object o =   redisUtil.hget("GOODCARD_"+memberMobile,item.getId().toString());
               if(null != o){
        MallGood tempMallGood = (MallGood) o;
        item.setGoodCartNum(tempMallGood.getGoodCartNum());
    }*/



    /**
     *
     * 添加购物车
     * http://127.0.0.1:8090/f/mall/web/v1/addGoodCart?memberMobile=15230060935&specsId=13&goodId=16&num=10
     * @param goodId
     * @param num
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("addGoodCart")
    public R addGoodCart(
            @RequestParam("specsId") Long specsId,
            @RequestParam("memberMobile") String memberMobile,
            @RequestParam("goodId") Long goodId,
            @RequestParam("num") Integer num,
            @RequestParam("type") String type,
            @RequestParam("isSelect") Integer isSelect,
            HttpServletRequest request,
            HttpServletResponse response){

        GoodSpecs goodSpecs  =  goodSpecsService.get(specsId);
        if(null == goodSpecs || goodSpecs.getStock() < num){
            if(type.equals("add")){
                return R.error(goodSpecs.getName()+"库存不足");
            }
        }
        MallGood mallGood = mallGoodService.getMin(goodId);
        mallGood.setGoodCartNum(num);
        mallGood.setPrice(goodSpecs.getPrice());
        mallGood.setUnit(goodSpecs.getName());
        mallGood.setSpecsId(goodSpecs.getId());
        mallGood.setIntegral(goodSpecs.getIntegral());
        mallGood.setIsSelect(isSelect);
        mallGood.setTotalPrice(num * goodSpecs.getPrice());
        mallGood.setTotalIntegral(num * goodSpecs.getIntegral());
        redisUtil.hset("GOODCARD_"+memberMobile, goodId+"_"+specsId, mallGood);
        Map map = redisUtil.hmget("GOODCARD_"+memberMobile);
        List result = new ArrayList();
        AtomicReference<Double> totalPrice = new AtomicReference<>(0d);
        AtomicReference<Double> totalIntegral = new AtomicReference<>(0d);
        if(null != map && map.size() > 0){
            map.entrySet().stream().forEach(item ->{
                MallGood m = (MallGood) ((Map.Entry)item).getValue();
                if(m.getGoodCartNum() > 0){
                    result.add(m);
                    totalPrice.updateAndGet(v -> new Double((double) (v + m.getTotalPrice())));
                    totalIntegral.updateAndGet(v-> new Double((double) (v + m.getTotalIntegral())));
                }
            });
        }
        return R.ok().put("l", result)
                .put("totalPrice",checkDouble(totalPrice.get()))
                .put("totalIntegral",checkDouble(totalIntegral.get()));
    }



    /**
     * 得到购物车列表
     * http://127.0.0.1:8090/f/mall/web/v1/getGoodCart?memberMobile=15230060935
     * @param memberMobile
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("getGoodCart")
    public R addGoodCart(
            @RequestParam("memberMobile") String memberMobile,
            HttpServletRequest request,
            HttpServletResponse response){
        Map map = redisUtil.hmget("GOODCARD_"+memberMobile);
        List result = new ArrayList();
        AtomicReference<Double> totalPrice = new AtomicReference<>(0d);
        AtomicReference<Double> totalIntegral = new AtomicReference<>(0d);
        if(null != map && map.size() > 0){
            map.entrySet().stream().forEach(item ->{
                MallGood m = (MallGood) ((Map.Entry)item).getValue();
                if(m.getGoodCartNum() > 0){
                    result.add(m);
                    totalPrice.updateAndGet(v -> new Double((double) (v + m.getTotalPrice())));
                    totalIntegral.updateAndGet(v-> new Double((double) (v + m.getTotalIntegral())));
                }
            });
        }
        return R.ok().put("l", result)
                .put("totalPrice",checkDouble(totalPrice.get()))
                .put("totalIntegral",checkDouble(totalIntegral.get()));
    }

    /**
     *  http://127.0.0.1:8090/f/mall/web/v1/cleanGoodCard?memberMobile=15230060935
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("cleanGoodCard")
    public R cleanGoodCard(
            @RequestParam("memberMobile") String memberMobile,
            HttpServletRequest request,
            HttpServletResponse response){
        redisUtil.del("GOODCARD_"+memberMobile);
        return R.ok();
    }





    /**
     * 创建订单 type == 1 1是金钱支付  2是积分支付
     * http://127.0.0.1:8090/f/mall/web/v1/createOrder?memberMobile=15230060935&selectStr=&address=测试&type=1
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("createOrder")
    public R createOrder(
            @RequestParam("selectStr") String selectStr,
            @RequestParam("memberMobile") String memberMobile,
            @RequestParam("address") String address,
            @RequestParam("type") Integer type,
            HttpServletRequest request,
            HttpServletResponse response){
        return createOrderFunction(selectStr,memberMobile,address,type,request,response);
    }




    R createOrderFunction(String selectStr,  String memberMobile,String address,Integer type,
                          HttpServletRequest request,  HttpServletResponse response ){
        //选中的购物车ID
        String [] idlist = selectStr.split(",");
        if(idlist.length == 0){
            return R.error("请选中一个要结算的商品");
        }
        Map<Long,List<MallGood>> chaidanMap = new HashMap<Long,List<MallGood>> ();
        for(String id: idlist){
            Object obj =  redisUtil.hget("GOODCARD_"+memberMobile, id);
            if(obj == null){
               /* return R.error("购物车取出异常");*/
                String goodId = id.split("_")[0];
                String specsId = id.split("_")[1];
                MallGood mallGood = mallGoodService.get(Long.parseLong(goodId));
                mallGood.setGoodCartNum(1);
                mallGood.setIsSelect(1);
                mallGood.setSpecsId(Long.parseLong(specsId));
                obj = mallGood;
            }
            MallGood mallGood = (MallGood) obj;
            if(mallGood.getMerchantId() == null){
                return R.error(mallGood.getName()+"供应商不存在");
            }

            //立即购买的逻辑
            String isNow = request.getParameter("isNow");
            String isNowNum = request.getParameter("isNowNum");
            if("Y".equals(isNow)){
                if(StringUtils.isNotEmpty(isNowNum)){
                    mallGood.setGoodCartNum(Integer.parseInt(isNowNum));
                }else {
                    mallGood.setGoodCartNum(1);
                }
            }

            GoodSpecs  goodSpecs  = goodSpecsService.get(mallGood.getSpecsId());
            MallGood tempGood = mallGoodService.get(mallGood.getId());


            if(tempGood.getIsShow().intValue() == 0){
                redisUtil.hdel("GOODCARD_"+memberMobile, id);
                return R.error(mallGood.getName()+"已下架");
            }

            if(mallGood.getGoodCartNum() > goodSpecs.getStock()){
                redisUtil.hdel("GOODCARD_"+memberMobile, id);
                return R.error(mallGood.getName()+"库存不足");
            }

            if(mallGood.getGoodCartNum() <= 0){
                mallGood.setGoodCartNum(1);
            }

            mallGood.setIntegral(goodSpecs.getIntegral());
            mallGood.setPrice(goodSpecs.getPrice());
            mallGood.setTotalPrice(goodSpecs.getPrice() * mallGood.getGoodCartNum());
            mallGood.setTotalIntegral(goodSpecs.getIntegral() *  mallGood.getGoodCartNum());
            mallGood.setUnit(goodSpecs.getName());
            if(null == chaidanMap.get(mallGood.getMerchantId())){
                List list = new ArrayList();
                list.add(mallGood);
                chaidanMap.put(mallGood.getMerchantId(),list);
            }else{
                chaidanMap.get(mallGood.getMerchantId()).add(mallGood);
            }
        }
        ShequMember shequMember =  shequMemberService.getByMobile(memberMobile);
        if(null == shequMember){
            return  R.error("会员不存在");
        }

        //开始创建订单
        String orderNo = SnowflakeIdWorker.getOrderNo("L");
        List<MallOrder> orderList = new ArrayList<>();
        for(Map.Entry<Long,List<MallGood>> item : chaidanMap.entrySet()){
            MallOrder mallOrder = new MallOrder();
            mallOrder.setOrderNo(orderNo);
            mallOrder.setOrderId(SnowflakeIdWorker.getOrderNo(""));
            //会员信息最后录入
            mallOrder.setMemberMobile(memberMobile);
            if(StringUtils.isNotEmpty(request.getParameter("linkMobile"))){
                mallOrder.setLinkMobile(request.getParameter("linkMobile"));
            }else{
                mallOrder.setLinkMobile(memberMobile);
            }
            mallOrder.setMemberName(shequMember.getRealName());
            mallOrder.setMemberId(shequMember.getId());
            mallOrder.setCommunityId(shequMember.getCommunityId());
            mallOrder.setCommunityName(shequMember.getCommunityName());
            //
            mallOrder.setPayStatus(0);
            mallOrder.setType(type);
            double totalPrice = 0d;
            int totalNumber = 0;
            double totalFreightMoney = 0d;
            for(MallGood good : item.getValue()){
                MallOrderLog mallOrderLog = new MallOrderLog();
                //商品数量
                totalNumber += good.getGoodCartNum();
                //邮费
                totalFreightMoney += good.getFreightMoney();
                //判断是否为积分支付 1是用钱 2是积分
                if(type.intValue() == 1){
                    totalPrice += good.getTotalPrice();
                    mallOrderLog.setPrice(good.getPrice());
                }else if(type.intValue() == 2){
                    totalPrice += good.getTotalIntegral();
                    mallOrderLog.setPrice(good.getIntegral());
                    if(good.getIntegral() <= 0){
                        return R.error(good.getName()+"【"+good.getUnit()+"】"+"不支持积分支付");
                    }
                }

                mallOrderLog.setGoodId(good.getId());
                mallOrderLog.setGoodName(good.getName());
                mallOrderLog.setGoodNum(good.getGoodCartNum());
                mallOrderLog.setGoodPic(good.getPic());
                mallOrderLog.setTotalNum(good.getGoodCartNum());
                mallOrderLog.setTotalPrice(mallOrderLog.getPrice() * mallOrderLog.getGoodNum());
                mallOrderLog.setOrderId(mallOrder.getOrderId());
                mallOrderLog.setFreightMoney(good.getFreightMoney());
                mallOrderLog.setSpecsId(good.getSpecsId());
                mallOrderLog.setSpecsName(good.getUnit());
                mallOrderLog.setGoodCatetoryId(good.getCategoryId());
                mallOrderLog.setGoodCatetoryName(good.getCategoryName());


                mallOrder.getMallOrderLogs().add(mallOrderLog);
                mallOrder.setUserId(good.getMerchantId());
                mallOrder.setUserName(good.getMerchantName());
            }
            if(totalPrice <= 0){
                return R.error("系统错误 -9 ,请重新下单");
            }
            //+油费
            //优惠金额
            mallOrder.setDiscountMoney(0d);
            mallOrder.setPayMoney(totalPrice + totalFreightMoney);
            mallOrder.setTotalMoney(totalPrice + totalFreightMoney);
            mallOrder.setFreightMoney(totalFreightMoney);
            mallOrder.setAddress(address);
            mallOrder.setTotalNum(totalNumber);
            mallOrder.setRemark(request.getParameter("remark"));
            orderList.add(mallOrder);
        }

        AtomicReference<Double> totalMoney = new AtomicReference<>(0d);
        AtomicReference<Double> payMoney = new AtomicReference<>(0d);
        AtomicInteger totalNumber = new AtomicInteger();
        AtomicReference<Double> totalFreightMoney = new AtomicReference<>(0d);

        orderList.forEach(item ->{
            totalMoney.updateAndGet(v -> new Double((double) (v + item.getTotalMoney())));
            payMoney.updateAndGet(v -> new Double((double) (v + item.getPayMoney())));
            totalNumber.addAndGet(item.getTotalNum());
            totalFreightMoney.updateAndGet(v -> new Double((double) (v + item.getFreightMoney())));
        });

        String K = UUID.randomUUID().toString().replace("-", "");
        redisUtil.set("ORDER_PAY"+K,orderList,60*60*60);
        return R.ok().put("k",K)
                .put("totalMoney",checkDouble(totalMoney.get()))
                .put("payMoney",checkDouble(payMoney.get()))
                .put("totalNumber",totalNumber)
                .put("orderList",orderList)
                .put("totalFreightMoney",totalFreightMoney.get())
                ;
    }

    /**
     *
     * http://127.0.0.1:8090/f/mall/web/v1/payOrder?key=&type=1
     * 支付订单 type 1是在线支付 2是积分支付
     * @param key
     * @param type
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("payOrder")
    public R payOrder(
            @RequestParam("key") String key,
            @RequestParam("type") Integer type,
            HttpServletRequest request,
            HttpServletResponse response){

        Object  obj  = redisUtil.get("ORDER_PAY"+key);
        if(null == obj){
            return R.ok("订单超时,请重新下单");
        }
        boolean b = false;
        List<MallOrder>  orderList = (List<MallOrder>) obj;
        if(orderList.size() == 0){
            return R.ok("异常订单,0商品");
        }
        Map map = null;
        Map appPayStr = new HashMap();
        try {
            if(type == 1){
                AtomicReference<Double> payMoney = new AtomicReference<>(0d);
                orderList.forEach(item ->{
                    payMoney.updateAndGet(v -> new Double((double) (v + item.getPayMoney())));
                });
                map =  createJsApi(orderList.get(0).getOrderNo(),payMoney.get(),request);
                b =  mallOrderService.saveOrderByWx(orderList);
            }
            //积分购买的相关逻辑
            else if(type == 2){
                b =  mallOrderService.saveOrderByJiFen(orderList);
            }
        }catch (Exception e){
            e.printStackTrace();
            return R.error(e.getMessage());
        }
        if(!b){
            return R.error("订单创建失败");
        }
        orderList.forEach(item ->{
            try {
                if(null != item.getUserId()){
                    WebSocketServer webSocketServer =  WebSocketServer.SOCKER_MAPING.get(item.getUserId());
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("type",9 );
                    jsonObject.put("msg","商城订单: 您有新订单,请及时处理");
                    webSocketServer.sendMessage(jsonObject.toJSONString());
                }

            }catch (Exception e){

            }
        });
        redisUtil.del("ORDER_PAY"+key);
        return R.ok("订单创建成功").put("jsApi", map);
    }


    /**
     *
     * http://127.0.0.1:8090/f/mall/web/v1/testPayOrder?key=
     * 支付订单 type 1是在线支付 2是积分支付
     * @param key
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("testPayOrder")
    public R testPayOrder(
            @RequestParam("key") String key,
            HttpServletRequest request,
            HttpServletResponse response){
        int type = 1;
        Object  obj  = redisUtil.get("ORDER_PAY"+key);
        if(null == obj){
            return R.ok("订单超时,请重新下单");
        }
        boolean b = false;
        List<MallOrder>  orderList = (List<MallOrder>) obj;
        if(orderList.size() == 0){
            return R.ok("异常订单,0商品");
        }
        Map map = null;
        Map appPayStr = new HashMap();
        try {
            if(type == 1){
                AtomicReference<Double> payMoney = new AtomicReference<>(0d);
                orderList.forEach(item ->{
                    payMoney.updateAndGet(v -> new Double((double) (v + item.getPayMoney())));
                });
                map =  createWxPay(request,response);
                b =  mallOrderService.saveOrderByWx(orderList);
            }
            //积分购买的相关逻辑
            else if(type == 2){
                b =  mallOrderService.saveOrderByJiFen(orderList);
            }
        }catch (Exception e){
            e.printStackTrace();
            return R.error(e.getMessage());
        }
        if(!b){
            return R.error("订单创建失败");
        }
        orderList.forEach(item ->{
            try {
                if(null != item.getUserId()){
                    WebSocketServer webSocketServer =  WebSocketServer.SOCKER_MAPING.get(item.getUserId());
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("type",9 );
                    jsonObject.put("msg","商城订单: 您有新订单,请及时处理");
                    webSocketServer.sendMessage(jsonObject.toJSONString());
                }

            }catch (Exception e){

            }
        });
        // redisUtil.del("ORDER_PAY"+key);
        return R.ok("订单创建成功").put("jsApi", map);
    }




    /**
     * 创建支付jsAPI
     * @param request
     * @return
     */
    Map createJsApi(String orderNo,Double totalMoney, HttpServletRequest request){
        //随机字符串
        String nonce_str = CommonUtil.CreateNoncestr();
        String basePath = request.getScheme() + "://"
                + request.getServerName() + request.getContextPath();
        WxPayHelper wxPayHelper = new WxPayHelper();
       /* *//*新的商户信息*//**/
        wxPayHelper.setApiKey(xcxConfigService.getDefalt().getApiKey());
        //小程序id
        wxPayHelper.setAppId(xcxConfigService.getDefalt().getAppId());
        //商户号
        wxPayHelper.setMchId(xcxConfigService.getDefalt().getMemchantNo());

    /*    wxPayHelper.setApiKey("irntxUYR0pmP1jNsKIO7MyQjqQcFMwWm");
        wxPayHelper.setAppId("wxe5bf1195025a6946");
        wxPayHelper.setMchId("1400343402");
*/
        //商品描述
        wxPayHelper.SetParameter("body", "购买商品消费"+checkDouble(totalMoney)+"元");
        wxPayHelper.SetParameter("nonce_str", nonce_str);
        //通知地址
        wxPayHelper.SetParameter("notify_url", basePath
                + "/f/mall/web/v1/wxCallBack");
        wxPayHelper.SetParameter("out_trade_no",orderNo);
        //标价金额
        wxPayHelper.SetParameter("total_fee", String.format("%.0f",totalMoney*100));
        //终端IP
        wxPayHelper.SetParameter("spbill_create_ip",
                IPUtils.getIpAddr(request));
        //交易类型
        wxPayHelper.SetParameter("trade_type", "APP");
        wxPayHelper.SetParameter("attach", "购买商品");
        try {
            Map m = wxPayHelper.createAppPay();
            return  m;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 生成访问微信支付jsapi

     * @param request
     * @return
     */
    private Map<String, String> createWxPay(HttpServletRequest request, HttpServletResponse response) {
        String params = "";
        Double totalPrice =100d;
        try {
            String nonce_str = CommonUtil.CreateNoncestr();
            String basePath = request.getScheme() + "://"
                    + request.getServerName() + request.getContextPath();
            WxPayHelper wxPayHelper = new WxPayHelper();
          /*  wxPayHelper.setApiKey("irntxUYR0pmP1jNsKIO7MyQjqQcFMwWm");
            wxPayHelper.setAppId("wxe5bf1195025a6946");
            wxPayHelper.setMchId("1400343402");*/
            wxPayHelper.setApiKey(xcxConfigService.getDefalt().getApiKey());
            //小程序id
            wxPayHelper.setAppId(xcxConfigService.getDefalt().getAppId());
            //商户号
            wxPayHelper.setMchId(xcxConfigService.getDefalt().getMemchantNo());
            wxPayHelper.SetParameter("body", "购买商品");
            wxPayHelper.SetParameter("nonce_str", nonce_str);
            wxPayHelper.SetParameter("notify_url", basePath
                    + "/f/AppParent/wxNotify");

            wxPayHelper.SetParameter("out_trade_no", SnowflakeIdWorker.getOrderNo("MEWY"));

            wxPayHelper.SetParameter("total_fee",String.format("%.0f",totalPrice*100));

            wxPayHelper.SetParameter("spbill_create_ip",
                    IPUtils.getIpAddr(request));

            wxPayHelper.SetParameter("trade_type", "APP");
            wxPayHelper.SetParameter("attach", "微信支付");

            return wxPayHelper.createAppPay();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * http://127.0.0.1:8090/f/mall/web/v1/wxCallBack?orderNo=
     * @return
     * @throws Exception
     */
    @RequestMapping("wxCallBack")
    @ResponseBody
    public void wxCallBack(HttpServletRequest request, HttpServletResponse response) throws Exception {
        if(wxCallBackHander(request, response)) {
            if(null != response.getWriter()) {
                response.getWriter().println(WXPAYOK);
            }
        }else {
            if(null != response.getWriter()) {
                response.getWriter().println(WXPAYNO);
            }
        }
        if(null != response.getWriter()) {
            response.getWriter().flush();
            response.getWriter().close();
        }

    }



    /**
     * 回掉处理防止并发
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    synchronized  boolean  wxCallBackHander(HttpServletRequest request, HttpServletResponse response) throws Exception {

        StringBuffer stringBuffer = new StringBuffer();
        BufferedReader bReader = request.getReader();
        String line = "";
        while ((line = bReader.readLine()) != null) {
            stringBuffer.append(line);
        }
        Map<String, String> xmlMap = XMLUtils.xml2Map(stringBuffer.toString());
        System.err.println("微信回调参数-------------------" + stringBuffer.toString());
        String resXml = null;
        if ("SUCCESS".equals(xmlMap.get("xml.result_code"))) {
            String out_trade_no = xmlMap.get("xml.out_trade_no");
            String total_fee = xmlMap.get("xml.total_fee");
            String transaction_id = xmlMap.get("xml.transaction_id");
            Hog.e("支付回调 时间 = {}，订单号 = {}，微信单号 ={}",
                    DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"), out_trade_no, transaction_id);
            if (com.alibaba.druid.util.StringUtils.isEmpty(transaction_id)
                    || com.alibaba.druid.util.StringUtils.isEmpty(total_fee) ||
                    com.alibaba.druid.util.StringUtils.isEmpty(out_trade_no)
            ) {
                return false;
            }
            /**
             * 支付回调参数验证  防止别人恶意篡改回调数据
             */
            if (!PayCheckSginUtils.checkWxSgin(xmlMap, xcxConfigService.getDefalt().getApiKey())) {
                return false;
            }


            //支付
            return mallOrderService.orderPayOk(out_trade_no,  transaction_id);

        }
        return  false;
    }

    /**
     * 回掉处理防止并发
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    synchronized  boolean  wxCallBackHanderDev(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String  out_trade_no = request.getParameter("orderNo");
        return mallOrderService.orderPayOk(out_trade_no, "test");
    }





    /**
     * 得到订单
     * http://127.0.0.1:8090/f/mall/web/v1/getOrderList?memberMobile=15230060935
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("getOrderList")
    public R getOrderList(
            @RequestParam("memberMobile") String memberMobile,
            @RequestParam("offset") Integer offset,
            @RequestParam("limit") Integer limit,
            HttpServletRequest request,
            HttpServletResponse response){
        MapBuild mapBuild = new MapBuild();
        mapBuild.setKV("memberMobile", memberMobile)
                .setKV("offset", offset*limit)
                .setKV("limit", limit);


        String payStatus = request.getParameter("payStatus");
        if(StringUtils.isNotEmpty(payStatus) && !payStatus.equals("0")){
            if(payStatus.equals("5")){
                mapBuild.put("payStatusList", "4,5,6");
            }else{
                mapBuild.put("payStatus", Integer.parseInt(payStatus));
            }
        }

        int count =  mallOrderService.count(mapBuild);
        int pageSum=(count-1)/limit+1;
        if(offset > pageSum-1){
            return R.error("没有更多了");
        }
        List<MallOrder> mallOrders =  mallOrderService.list(mapBuild);
        mallOrders.stream().forEach(item ->{
            item.setMallOrderLogs(mallOrderLogService.list(MapBuild.getInstand().setKV("orderId", item.getOrderId())));
        });
        return R.ok().put("l",  mallOrders).put("serviceMobile", "0310-1234567");
    }






    /**
     * 得到订单详情
     * http://127.0.0.1:8090/f/mall/web/v1/getOrderDetail?id=
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("getOrderDetail")
    public R getOrderDetail(
            @RequestParam("id") Long id ,
            HttpServletRequest request,
            HttpServletResponse response){
        MallOrder mallOrder  = mallOrderService.get(id);
        List<MallOrderLog>  logList =  mallOrderLogService.list(MapBuild.getInstand().setKV("orderNo", mallOrder.getOrderNo()));
        mallOrder.setMallOrderLogs(logList);
        return R.ok().put("i",  mallOrder);
    }


    /**
     * http://127.0.0.1:8090/f/mall/web/v1/tuidan?orderId=
     * 取消订单 根据订单ID
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping("/tuidan")
    public R tuidan(@RequestParam("orderId")String orderId){
        try {
            return R.ok(mallOrderService.tuiHuoByOrderId(orderId)) ;
        }catch (Exception e){
            e.printStackTrace();
            return R.error(e.getMessage());
        }

    }

    /**
     * http://127.0.0.1:8090/f/mall/web/v1/lockOrder?orderId=
     * 取消订单 根据订单ID
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping("/lockOrder")
    public R lockOrder(@RequestParam("orderId")String orderId){
        MallOrder mallOrder  =  mallOrderService.getByOrderId(orderId);
        if(null == mallOrder
                || !(mallOrder.getPayStatus().intValue() == 1
                || mallOrder.getPayStatus().intValue() == 2))
        {
            return R.error("该订单不支持退款");
        }
        int row =  mallOrderService.updatePayStatusByOrderId(orderId, 6,null,null,null,null);
        if(row <= 0){
            return R.error("订单状态修改失败");
        }
        return R.ok("发起退款成功，请耐心等待系统审核");
    }



}
